<?php
/**
 * Class Wechat
 * Desc 公众号
 * Create on 2021/10/20 17:19
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use think\cache\driver\Redis;

class Wechat extends Base
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    private function _request($curl,$https=true,$method='GET',$data=null){
        // 创建一个新cURL资源
        $ch = curl_init();

        // 设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $curl);  //要访问的网站
        //启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch, CURLOPT_HEADER, false);
        //将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if($https){
            //FALSE 禁止 cURL 验证对等证书（peer's certificate）。
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //验证主机
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }
        if($method == 'POST'){
            curl_setopt($ch, CURLOPT_POST, true); //发送 POST 请求
            //全部数据使用HTTP协议中的 "POST" 操作来发送。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }


        // 抓取URL并把它传递给浏览器
        $content = curl_exec($ch);

        //关闭cURL资源，并且释放系统资源
        curl_close($ch);

        return $content;
    }

    public function _getAccessToken(){
        $domain = $_SERVER['HTTP_HOST'];
        $redis = new Redis();
        $domain_official_access_token = $redis->get($domain.'_official_access_token');
        if($domain_official_access_token) {
            return $domain_official_access_token->access_token;
        }
        $this->_appid =$this->configObj->official_account_appid;//公众号appid
        $this->_appsecret =$this->configObj->official_account_appsecret;//公众号秘钥
        $curl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_appid.'&secret='.$this->_appsecret;
        $content = $this->_request($curl);
        $cont = json_decode($content);
        $redis->set($domain.'_official_access_token',$cont,3600);
        return $cont->access_token;

    }
}